package JZOffer;

import java.util.Stack;

public class _13 {
    class Solution {
        public ListNode FindKthToTail(ListNode head,int k) {
            if (head == null || k == 0) return null;
            Stack<Integer> stack = new Stack<Integer>();
            ListNode mov = head;
            int len = 0;
            while (mov != null) {
                stack.push(mov.val);
                mov = mov.next;
                len++;
            }
            if(k>len) return null;
            ListNode res = new ListNode(stack.pop());
            ListNode pre = res;
            while (k>1) {
                ListNode temp =  new ListNode(stack.pop());
                pre = res;
                temp.next = pre;
                res = temp;
                k--;
            }
            return res;
        }
    }

    Solution getSolution() {
        return new Solution();
    }

    public static void main(String args[]) {
        _13 c = new _13();
        _13.Solution s = c.getSolution();
        ListNode L1 = new ListNode(3);
        ListNode L2 = new ListNode(4);
        ListNode L3 = new ListNode(5);
        ListNode L4 = new ListNode(6);
        ListNode L5 = new ListNode(7);
        L1.next = L2;
        L2.next = L3;
        L3.next = L4;
        L4.next = L5;
        ListNode res = s.FindKthToTail(L1,2);
        while (res != null){
            System.out.println(res.val);
            res = res.next;
        }
    }
}
